package com.linln.admin.system.controller;

import com.linln.admin.system.service.AppService;
import com.linln.admin.system.validator.RoleValid;
import com.linln.common.constant.AdminConst;
import com.linln.common.enums.ResultEnum;
import com.linln.common.enums.StatusEnum;
import com.linln.common.exception.ResultException;
import com.linln.common.utils.EntityBeanUtil;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.StatusUtil;
import com.linln.common.utils.ValidationUtil;
import com.linln.common.vo.ResultVo;
import com.linln.component.actionLog.action.RoleAction;
import com.linln.component.actionLog.action.StatusAction;
import com.linln.component.actionLog.annotation.ActionLog;
import com.linln.component.actionLog.annotation.EntityParam;
import com.linln.component.shiro.ShiroUtil;
import com.linln.modules.system.domain.Menu;
import com.linln.modules.system.domain.Role;
import com.linln.modules.system.domain.User;
import com.linln.modules.system.repository.RoleRepository;
import com.linln.modules.system.repository.UserRepository;
import com.linln.modules.system.service.MenuService;
import com.linln.modules.system.service.RoleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.*;

/**
 * @author 小懒虫
 * @date 2018/8/14
 */
@Controller
@RequestMapping("/system/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private AppService appService;

    @Autowired
    private RoleRepository roleRepository;

    @PersistenceContext
    private EntityManager entityManager;


    /**
     * 列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("system:role:index")
    public ResponseEntity<?> index(Model model, Role role){


        return appService.layTable(roleRepository, before -> {

                    // 添加模板变量

                    return model;

                },

                after -> {

                    // 返回JSON数据
                    return null;
                },

                "/system/role/index",

                (pageResult) -> {
                    // 在这里处理 pageResult
                    // 例如：修改每一条数据
//                    pageResult.getContent().forEach(item -> {
//                        // 对每一项数据进行处理
//                    });
                }

        );




    }

    /**
     * 跳转到添加页面
     */
    @RequestMapping("/form")
    @RequiresPermissions("system:role:form")
    public ResponseEntity<?> form(Model model, @EntityParam Role role) throws Exception{

        return appService.form(roleRepository, "/system/role/form", (isEdit) -> {

                    return model;

                }, (data) -> {

                    // 保存前数据校验
                    List<ValidationUtil.ValidationRule<?>> rules = new ArrayList<>();
                    // 执行校验
                    return ValidationUtil.validateFields(rules);

                }, (data) -> {

                    if (role.getId() != null) { // 编辑
                        Role beRole = roleRepository.getById(role.getId());
                        String[] fields = {"users", "menus"};
                        EntityBeanUtil.copyProperties(beRole, role, fields); // 将beMenu 字段复制到 menu
                    }

                    return role;

                },

                (data) -> {
                    // 保存角色数据

                });

    }


    /**
     * 跳转到授权页面
     */
    @RequestMapping("/auth")
    @RequiresPermissions("system:role:auth")
    public ResponseEntity<?> auth(Model model, @RequestParam(value = "id") Role role, @RequestParam(value = "authId", required = false) HashSet<Menu> menus) throws Exception{

        return appService.form(roleRepository, "/system/role/auth", (isEdit) -> {

                // 获取指定角色权限资源
                Role beRole = roleRepository.getById(role.getId());
                Set<Menu> authMenus = beRole.getMenus();
                // 获取全部菜单列表
                List<Menu> list = menuService.getListBySortOk();
                // 融合两项数据
                list.forEach(menu -> {
                    if(authMenus.contains(menu)){
                        menu.setRemark("auth:true");
                    }else {
                        menu.setRemark("");
                    }
                });
                model.addAttribute("menus", list);

                return model;

            },
            (isEdit, vo) -> {

                model.addAttribute("vo", vo);
                // 你可以在这里添加其他逻辑
                return model;
            }, (data) -> {

                // 保存前数据校验
                List<ValidationUtil.ValidationRule<?>> rules = new ArrayList<>();
                // 执行校验
                return ValidationUtil.validateFields(rules);

            }, (data) -> {

                role.setMenus(menus);

                // 数据处理
                return role;
            },

            (data) -> {
                // 保存后续逻辑在这写
            });
    }


//
//    /**
//     * 保存授权信息
//     */
//    @PostMapping("/auth")
//    @RequiresPermissions("system:role:auth")
//    @ResponseBody
//    @ActionLog(key = RoleAction.ROLE_AUTH, action = RoleAction.class)
//    public ResultVo auth(
//            @RequestParam(value = "id", required = true) Role role,
//            @RequestParam(value = "authId", required = false) HashSet<Menu> menus){
//        // 不允许操作管理员角色数据
//        if (role.getId().equals(AdminConst.ADMIN_ROLE_ID) &&
//                !ShiroUtil.getSubject().getId().equals(AdminConst.ADMIN_ID)){
//            throw new ResultException(ResultEnum.NO_ADMINROLE_AUTH);
//        }
//
//        // 更新角色菜单
//        role.setMenus(menus);
//
//        // 保存数据
//        roleService.save(role);
//        return ResultVoUtil.SAVE_SUCCESS;
//    }


}
